package com.example.androidcompletesec.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.example.androidcompletesec.R;

public class FileIO extends Activity {
	EditText mEdit;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fileio);
		
		mEdit = (EditText) findViewById(R.id.edittext);
	}
	
	public void mOnClick(View v){
		switch(v.getId()){
		case R.id.save:
			try {
				FileOutputStream fos = openFileOutput("text.txt", Context.MODE_WORLD_READABLE);
				String str = mEdit.getText().toString();
				fos.write(str.getBytes());
				fos.close();
				mEdit.setText("write success");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.load:
			try {
				FileInputStream fis = openFileInput("text.txt");
				byte[] data = new byte[fis.available()];
				while(fis.read(data) != -1){;}
				fis.close();
				mEdit.setText(new String(data));
			} catch (FileNotFoundException e) {
				mEdit.setText("File Not Found");
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e){ ;
			}
			break;
		case R.id.loadres:
			InputStream fres = getResources().openRawResource(R.raw.restext);
			byte[] data = null;
			try {
				data = new byte[fres.available()];
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				while(fres.read(data) != -1){;}
			} catch (IOException e) {
				e.printStackTrace();
				try {
					fres.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			mEdit.setText(new String(data));
			break;
		case R.id.delete:
			if(deleteFile("text.txt")){
				mEdit.setText("delete Success");
			}else{
				mEdit.setText("delete fail");
			}
			break;
		}
	}
}
